package com.apop.common.config.action;

import com.alibaba.fastjson.JSONObject;
import com.apop.common.util.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.util.*;

/**
 * ActionConfig
 * Author: zjy
 * Date: 2021/11/9  15:23
 * Describe: TODO
 */
@Configuration
@Slf4j
public class ActionConfig {

    private static final String ACTION_PATTERN = "actions/*.xml";

    @Bean(name = "actionManager")
    public ActionManager actionManager() {
        return loadActionData();
    }

    private String getCurrentPath() {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length());
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path.replace("classes/", "");
    }

    /**
     * 加载
     *
     * @return
     */
    private ActionManager loadActionData() {
        ActionManager ret = new ActionManager();
        try {
            // 遍历action下的xml
            Resource[] resources = new PathMatchingResourcePatternResolver().
                    getResources(ResourceUtils.CLASSPATH_URL_PREFIX + ACTION_PATTERN);
            // 遍历文件内容
            for (Resource resource : resources) {

                Action action = new Action();
                // 创建一个SAXReader解析器
                SAXReader reader = new SAXReader();
                // 读取xml文件,转换成Document结点 这边必须通过InputStream读取
                Document doc = reader.read(resource.getInputStream());

                // 获取根节点
                Map<String, Object> map = XmlUtil.parseXmlDoc(doc);
                Map<String, Object> actionData = (Map) map.get("action");
                if (actionData != null) {
                    Map<String, Object> request = (Map) actionData.get("request");
                    if (request != null) {

                        Integer serviceId = Integer.valueOf((String) request.get("serviceId"));
                        action.setServiceId(serviceId);

                        String sql = (String) request.get("sql");
                        action.setSql(sql);

                        String liveBosUrl = (String) request.get("targetUrl");
                        action.setTargetUrl(liveBosUrl);

                        Map paramProcessors = (Map) request.get("paramProcessors");
                        if(paramProcessors!=null){
                            Set<String> set = paramProcessors.keySet();
                            List<String> list = new ArrayList<>();
                            for (String key : set) {
                                String method = (String) paramProcessors.get(key);
                                list.add(method);
                            }
                            action.setParamProcessors(list);
                        }

                        Map postProcessors = (Map) request.get("postProcessors");
                        if(postProcessors!=null){
                            Set<String> set = postProcessors.keySet();
                            List<String> list = new ArrayList<>();
                            for (String key : set) {
                                String method = (String) postProcessors.get(key);
                                list.add(method);
                            }
                            action.setPostProcessors(list);
                        }

                        String params = (String) request.get("params");
                        if (params != null) {
                            action.setParams(params);
                        }

                        String type = (String) request.get("type");
                        if (type != null) {
                            action.setType(type);
                        }

                        Integer timeout = (Integer) request.get("timeout");
                        if (timeout != null) {
                            action.setTimeOut(timeout);
                        }

                        String httpMethod = (String) request.get("httpMethod");
                        if (httpMethod != null) {
                            action.setHttpMethod(httpMethod);
                        }

                        if ("http".equals(type)) {
                            Integer mode = Integer.valueOf((String) request.get("mode"));
                            action.setMode(mode);
                        }

                    }
                    Map<String, Object> response = (Map) actionData.get("response");
                    if (response != null) {
                        String resultType = (String) response.get("resultType");
                        if (resultType != null) {
                            action.setResultType(resultType);
                        }
                    }
                    // 添加action到List
                    ret.actionList.add(action);
                    if (log.isDebugEnabled()) {
                        log.debug("加载 " + resource.getFilename() + " 成功！");
                    }
                }
            }
            Collections.sort(ret.actionList);
            log.info("成功 添加 " + ret.actionList.size() + "个 actions！");
            // 加载mock数据
            initMock(ret);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        return ret;
    }

    /**
     * 加载mock数据
     */
    private void initMock(ActionManager ret) {

        // 统计信息mock
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cumulativeAcceptance", 80454);
        jsonObject.put("cumulativeSettlement", 80448);
        jsonObject.put("evaluationNumber", 78215);
        jsonObject.put("favorableRate", 99.8f);
        ret.mockData.put(102, jsonObject.toJSONString());
    }
}
